
package com.hlkj.pay.config;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hlkj.framework.logging.config.BodyReaderHttpServletRequestWrapper;

import cn.hutool.http.ContentType;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhou.long
 * @date 2024/10/09 20:43
 */
@Slf4j
@Component
public class BodyReaderFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("BodyReaderFilter init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 包装 HttpServletRequest
        ServletRequest requestWrapper = null;
        String contentType = request.getContentType();
        if (StringUtils.hasText(contentType) && (ContentType.JSON.getValue().equals(contentType))) {
            if (request instanceof HttpServletRequest) {
                requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
            }
        }
        // 包装原始 response
        if (null == requestWrapper) {
            chain.doFilter(request, response);
        }
        else {
            chain.doFilter(requestWrapper, response);
        }
    }
}
